# -*- coding:utf-8 -*-
import json
import logging
import random
import time
import execjs
import os
import requests
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
from wipo.libs import config


def get_ua():
    first_num = random.randint(55, 62)
    third_num = random.randint(0, 3200)
    fourth_num = random.randint(0, 140)
    os_type = [
        '(Windows NT 6.1; WOW64)', '(Windows NT 10.0; WOW64)', '(X11; Linux x86_64)',
        '(Macintosh; Intel Mac OS X 10_12_6)'
    ]
    chrome_version = 'Chrome/{}.0.{}.{}'.format(first_num, third_num, fourth_num)

    ua = ' '.join(['Mozilla/5.0', random.choice(os_type), 'AppleWebKit/537.36',
                   '(KHTML, like Gecko)', chrome_version, 'Safari/537.36']
                  )
    return ua


def encode_param(param):
    with open(BASE_DIR + "\\libs\\LZStringJQ.js", 'r', encoding='utf-8') as f:
        jsData = f.read()
    com = execjs.compile(jsData)
    x = com.call("getCurrentStateString", param)
    qz = x.replace('+', ' ')
    return qz


def get_proxy(url, wait):
    params = {
        "account": config.account,
        "accountKey": config.accountKey,
        "num": config.num,
        "cityId": config.city
    }
    try:
        time.sleep(wait)
        resp_js = requests.get(config.dby_url, params=params)
        resp = json.loads(resp_js.text)
        if resp["code"] == "200":
            pro_ip = resp["data"][0]["ip"]
            pro_port = resp["data"][0]["port"]
            ip = '{}:{}'.format(pro_ip, pro_port)
            proxies = {
                "http": "http://" + ip,
            }
            resp = requests.get(url, proxies=proxies)
            s_code = resp.status_code
            if s_code == 200:
                return ip
            else:
                return
    except Exception as e:
        logging.error("获取代理IP异常: {}".format(e))
        return
